// Package for Configurable figure and equation numbering per section, see: https://typst.app/universe/package/i-figured
#import "@preview/i-figured:0.2.4"
// Package for showing Chinese fake bold, see: https://typst.app/universe/package/cuti/
#import "@preview/cuti:0.3.0": show-cn-fakebold
#import "variables.typ": *
#import "variables.typ"
#import "tables.typ"

#let author(name_zh, name_en, insts: ()) = {
  if type(insts) != array {
    insts = (insts,)
  }
  (name_zh: name_zh, name_en: name_en, insts: insts)
}

#let institute(name_zh, name_en) = {
  (name_zh: name_zh, name_en: name_en)
}

// 参考自 https://github.com/werifu/HUST-typst-template/blob/5261d9202bdd0eefae0f8922b32770f02cf15e4f/utilities/set-heading.typ
#let show_heading(body) = {
  set heading(numbering: "1.1.1.1")

  // 参考自 https://github.com/nju-lug/modern-nju-thesis/blob/main/utils/custom-heading.typ
  show heading: it => {
    if it != none {
      set par(first-line-indent: 0em)
      if it.has("numbering") and it.numbering != none {
        numbering(it.numbering, ..counter(heading).at(it.location()))
        [ ]
      }
      it.body
    } else {
      ""
    }
  }
  show heading: it => block(it)
  show heading.where(level: 1): set block(above: 8pt, below: 8pt)
  show heading.where(level: 2): set block(above: 8pt, below: 8pt)
  show heading.where(level: 3): set block(above: 5pt, below: 5pt)
  // 一级标题*字体为4号黑体*
  show heading.where(level: 1): set text(weight: "regular", font: 字体.黑体, size: 字号.四号)
  // 二级标题 *字体为5号黑体*
  show heading.where(level: 2): set text(weight: "regular", font: 字体.黑体, size: 字号.五号)
  // 三级标题 *字体为5号宋体*
  show heading.where(level: 3): set text(weight: "regular", font: 字体.宋体, size: 字号.五号)
  // 第四及以下层次（款）题序和标题用小四号黑体字；
  show heading.where(level: 4): set text(weight: "regular", font: 字体.黑体, size: 字号.小四)
  show heading: i-figured.reset-counters.with(extra-kinds: ("image",))

  body
}

#let show_math(body) = {
  set math.equation(supplement: [公式])
  show math.equation: i-figured.show-equation.with(numbering: "(1-1)")
  body
}

#let show_figure(body) = {
  show figure.where(kind: "algorithm"): i-figured.show-figure.with(
    extra-prefixes: (algorithm: "alg:"),
    numbering: "1-1",
  )
  show figure.where(kind: "algorithm"): set figure(supplement: "程序")
  show figure.where(kind: "image"): i-figured.show-figure.with(
    extra-prefixes: (image: "img:"),
    numbering: "1-1",
  )
  show figure.where(kind: table): i-figured.show-figure.with(numbering: "1-1")

  show figure.where(kind: "image"): it => {
    counter(figure.where(kind: "subimage")).update(0)
    it
  }
  show figure.where(kind: "subimage"): set figure(numbering: "(a)", supplement: "")
  show figure.where(kind: "subimage"): set figure.caption(separator: "")

  show figure: set text(size: 字号.小五)

  show figure: set text(font: 字体.黑体)
  show figure.where(kind: table): set figure.caption(position: top)
  show figure.caption: set par(spacing: 0.5em)
  show figure.where(kind: table): set figure(supplement: "表")
  show figure.where(kind: "image"): set figure(supplement: "图")
  show figure: set align(center)
  show figure: it => {
    block(it, above: 1em, below: 1em)
    // v(0.5em)
    // it
    // v(0.5em)
  }

  body
}

#let show_appendix(it) = {
  counter(heading).update(0)
  set heading(supplement: "附录")
  show heading.where(level: 1): set heading(numbering: "附录A")
  show heading.where(level: 2): set heading(numbering: "A.1")

  // show regex("[\u4e00-\u9fa5]"): set text(font: "Sarasa Mono SC")
  show raw: set text(font: ("JetBrainsMono NFM", ..字体.宋体), size: 字号.小六)
  show raw: set text(top-edge: "cap-height", bottom-edge: "baseline")
  show raw: set par(leading: 1em, spacing: 1em, justify: false)

  it
}

#let show_body_style(body) = {
  // *正文部分, 字体为5号宋体*
  set text(font: 字体.宋体, size: 字号.五号, lang: "zh")

  show: show-cn-fakebold

  // 用于模仿 word 排版方式
  // See: https://github.com/typst/typst/issues/106#issuecomment-2041051807
  set text(top-edge: 0.7em, bottom-edge: -0.3em)
  // set block(stroke: blue)
  set par(spacing: 5pt, leading: 5pt, first-line-indent: 2em, justify: true)
  show: show_figure
  show: show_math
  show: show_heading

  body
}

// This function gets your whole document as its `body` and formats
// it as an article in the style of the IEEE.
#let cjc(
  // The paper's title.
  title_zh: [Paper Title],
  title_en: [Paper Title],
  // An array of authors. For each author you can specify a name,
  // department, organization, location, and email. Everything but
  // but the name is optional.
  authors: (),
  // The paper's abstract. Can be omitted if you don't have one.
  abstract_zh: none,
  keywords_zh: (),
  abstract_en: none,
  keywords_en: (),
  // The result of a call to the `bibliography` function or `none`.
  bib: none,
  // The paper's content.
  body,
  appendix: none,
) = {
  // Set document metadata.
  set document(title: title_zh, author: authors.map(author => author.name_zh))

  // Extract institutions from authors
  let insts = authors.map(it => it.insts).flatten().dedup()

  set page(
    paper: "a4",
    // The margins depend on the paper size.
    margin: (x: 2.0cm, y: 2.6cm),
    header-ascent: 2.6cm - 1.7cm - 9pt,
    header: context {
      let num = counter(page).get().at(0)
      if num == 1 {
        [
          #set text(size: 字号.小五)
          #set par(spacing: 15pt - 9pt)

          #grid(align: (left, center, right), columns: (auto, 1fr, auto), [
            第01卷#h(1em)第1期

            2025年6月
          ], [
            计#h(1em)算#h(1em)机#h(1em)学#h(1em)报

            CHINESE JOURNAL OF COMPUTERS
          ], [
            Vol. 01#h(1em)No. 1

            June. 2025
          ])
          #place(dy: 1.5pt)[#line(stroke: 0.5pt, length: 100%)]
          #place(dy: 2.5pt)[#line(stroke: 0.5pt, length: 100%)]
        ]
      } else {
        [
          #set text(size: 字号.小五)
          #if (calc.even(num)) [
            #grid(align: (left, center, right), columns: (auto, 1fr, auto), [
              #counter(page).get().at(0)
            ], [
              计算机学报
            ], [
              2025年
            ])
          ] else [
            #grid(align: (left, center, right), columns: (auto, 1fr, auto), [
              1期
            ], [
              作者名等：论文题目
            ], [
              #counter(page).get().at(0)
            ])
          ]

          #place(dy: 1.5pt)[#line(stroke: 0.5pt, length: 100%)]
        ]
      }
    },
    footer: context {
      let num = counter(page).get().at(0)
      if num == 1 {
        [
          #set text(font: 字体.宋体, size: 字号.六号)
          #place(dy: -10em)[
            ———————————————
          ]
        ]
      }
    },
  )

  // *正文部分, 字体为5号宋体*
  set text(font: 字体.宋体, size: 字号.五号)

  show: show-cn-fakebold

  // 用于模仿 word 排版方式
  // See: https://github.com/typst/typst/issues/106#issuecomment-2041051807
  set text(top-edge: 0.7em, bottom-edge: -0.3em)
  // set block(stroke: blue)

  [
    // MARK: ZH
    // 中文部分
    #set par(spacing: 5pt, leading: 5pt)
    #show heading: it => block(it)

    #v(2 * 22pt)

    #set par(justify: true)
    #set align(center)
    #[
      #show heading: set text(weight: "regular", font: 字体.黑体, size: 字号.二号)
      #heading(level: 1)[
        #title_zh
      ]
    ]

    #v(16pt)
    #scale(x: 66%)[
      #text(font: 字体.仿宋, size: 字号.三号)[
        #{
          authors
            .map(it => {
              let a = it
              // find references
              let refs = a.insts.map(ai => str(insts.position(i => i == ai) + 1)).join(",")
              [#a.name_zh#super([#refs])]
            })
            .join(h(1em))
        }
      ]
    ]
    #v(16pt)

    // *字体为6号宋体*
    // *中英文单位名称、作者姓名须一致*
    // (单位全名 部门(系)全名, 市(或直辖市) 国家名 邮政编码)
    // 论文定稿后，作者署名、单位无特殊情况不能变更。若变更，须提交签章申请，国家名为中国可以不写，省会城市不写省的名称，其他国家必须写国家名。
    #{
      insts
        .enumerate()
        .map(it => {
          let inst = it.at(1)
          let idx = it.at(0)
          text(font: 字体.宋体, size: 字号.六号)[
            #super([#{idx + 1})])#inst.name_zh
          ]
          linebreak()
        })
        .join()
    }
    #v(7.5pt * 0.8)

    #set align(left)
    #set text(font: 字体.宋体, size: 字号.小五)

    *摘#h(1em)要#h(1em)* #abstract_zh

    #par(hanging-indent: 4em)[
      *关键词#h(1em)* #keywords_zh.join("；")
    ]

    *中国法分类号* TP311.5#h(3em)*DOI号* \*投稿时不提供DOI号\*

    #v(12pt)
    // MARK: EN
    // 英文部分
    #set align(center)

    #[
      #show heading: set text(weight: "bold", font: "Times New Roman", size: 字号.四号)
      #heading(level: 1)[
        #title_en
      ]
    ]

    #v(5pt)
    #text(font: "Times New Roman", size: 字号.五号)[
      #{
        authors
          .map(it => {
            let a = it
            // find references
            let refs = a.insts.map(ai => str(insts.position(i => i == ai) + 1)).join(",")
            [#a.name_en#super([#refs])]
          })
          .join(h(1em))
      }
    ]
    #v(9pt)

    // *字体为6号宋体*
    // *中英文单位名称、作者姓名须一致*
    // (单位全名 部门(系)全名, 市(或直辖市) 国家名 邮政编码)
    // 论文定稿后，作者署名、单位无特殊情况不能变更。若变更，须提交签章申请，国家名为中国可以不写，省会城市不写省的名称，其他国家必须写国家名。
    #{
      insts
        .enumerate()
        .map(it => {
          let inst = it.at(1)
          let idx = it.at(0)
          text(font: "Times New Roman", size: 字号.六号)[
            #super([#{idx + 1})])#inst.name_en
          ]
          linebreak()
        })
        .join()
    }
    #v(7.5pt * 0.8)

    #set align(left)
    #set text(font: "Times New Roman", size: 字号.五号)

    #grid(columns: (auto, 1fr), column-gutter: 0.5em, row-gutter: 5pt, [*Abstract*], [
      #abstract_en
    ], [*Key words*], [
      #keywords_en.join("; ")
    ])
    #v(16pt)
  ]

  set page(columns: 2)
  set par(spacing: 5pt, leading: 5pt, first-line-indent: 2em, justify: true)
  show: show_figure
  show: show_math
  show: show_heading

  // columns(2)[
  body
  // ]

  show heading: set align(center)
  set bibliography(title: [参#h(1em)考#h(1em)文#h(1em)献])
  show heading: set align(horizon)
  show heading: set block(height: 3em)
  show heading: set text(size: 字号.五号)


  // Display bibliography.
  bib
  // if appendix != none {
  //   pagebreak(weak: true)
  //   show: show_appendix
  //   appendix
  // }
}
